/**
 * Created by xxcao on 2017/7/4.
 */
var sql = require('./sqlMapping');
var util = require('../util/util');
var code = require('../util/code');

module.exports = {
    login:function (req, res) {

        if (util.isParameterEmpty(req.body.user_name, req.body.password, req.body.code)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (req.body.code.toLowerCase() !== req.session.validCode.toLowerCase()) {
            res.json(util.toJson(code.NOT_EXISTED, '验证码不对'));
            return;
        }
        mysqlPool.getConnection(function (err, connection) {
            if (err) {
                 res.json(util.toJson(code.DATABASE_CONNECTION_ERROR,'数据库连接错误'));
                 return;
            }
            var pwd = util.getMD5String(req.body.password);
            var param = [req.body.user_name, pwd];
            connection.query(sql.user.findOne, param, function (err, result) {
                if (err === null && result && result.length > 0){
                    if (parseInt(result[0]['is_hr']) === 1) {
                        req.session.user = result[0]['user_id'];
                        res.json(util.toJson(code.OPERATE_SUCCESS, '登录成功', result[0]));
                    } else {
                        req.session.user = null;
                        res.json(util.toJson(code.IS_NOT_CAN,'您没有权限登录此系统'));
                    }
                } else {
                    req.session.user = null;
                    res.json(util.toJson(1000,'用户不存在'));
                }
                connection.release();
            })
        })
    },
    logout:function (req, res) {
        if (util.isParameterEmpty(req.body.user_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req,'POST')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        req.session.user = null;
        res.render('home',{});
    },
    enquiry:function (req, res) {
        if (util.isParameterEmpty(req.query.user_id, req.query.name, req.query.start, req.query.end, req.query.department, req.query.company, req.query.page)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req,'GET')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        if (parseInt(req.query.page) < 0){
            res.json(util.toJson(code.IS_NOT_CAN, '请输入合法的参数'));
            return;
        }
        var params1 = [req.query.start, req.query.end, req.query.name];
        var params2 = [req.query.start, req.query.end, req.query.name];
        var sql1 = sql.enquiry.dutyRecord;
        var sql2 = sql.enquiry.leaveAsk;

        if(req.query.department.indexOf('选择') < 0) {
            params1.push(req.query.department);
            params2.push(req.query.department);
            sql1 = sql1 + ' and c.name = ? ';
            sql2 = sql2 + ' and c.name = ? ';
        }
        if(req.query.company.indexOf('选择') < 0) {
            params1.push(req.query.company);
            params2.push(req.query.company);
            sql1 = sql1 + ' and d.name = ? ';
            sql2 = sql2 + ' and d.name = ? ';
        }
        var lastSql = sql.enquiry.findRecordNormal1 + sql1 + ' union ' + sql2 + sql.enquiry.findRecordNormal2;
        var pageSize = util.pageSize();
        var offset = util.pageSize() * req.query.page;
        var params = params1.concat(params2);
        params.push(pageSize);
        params.push(offset);
        mysqlPool.getConnection(function (err, connection) {
            if (err) {
                res.json(util.toJson(code.DATABASE_CONNECTION_ERROR,'数据库连接错误'));
                return;
            }

            new Promise(function (resolve) {
                connection.query(sql.user.findUser, [req.query.name], function (err, result) {
                    if (err === null && result && result.length > 0){
                        resolve(result[0]);
                    } else {
                        res.json(util.toJson(1000 ,'数据库中貌似没有姓名为【'+ req.query.name +'】的人'));
                        connection.release();
                    }
                });
            }).then(function (result) {
                connection.query(lastSql, params, function (err, result) {
                    if (err === null && result && result.length >= 0){
                        res.json(util.toJson(code.OPERATE_SUCCESS,'查询数据成功',result));
                    } else {
                        res.json(util.toJson(1000 ,'查询数据失败'));
                    }
                    connection.release();
                });
            });
        })
    },
    saveCode:function (req, res, code) {
        req.session.validCode = code;
    },
    getEnquiryPage:function (req, res) {
        if (util.isParameterEmpty(req.query.user_id, req.query.name)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req,'GET')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        res.render('enquiry',{user_id:req.query.user_id, name:req.query.name});
    },
    enquiryCount:function (req, res) {
        if (util.isParameterEmpty(req.query.user_id, req.query.name, req.query.start, req.query.end, req.query.department, req.query.company)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req,'GET')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        var params1 = [req.query.start, req.query.end, req.query.name];
        var params2 = [req.query.start, req.query.end, req.query.name];
        var sql1 = sql.enquiry.dutyRecord;
        var sql2 = sql.enquiry.leaveAsk;

        if(req.query.department.indexOf('选择') < 0) {
            params1.push(req.query.department);
            params2.push(req.query.department);
            sql1 = sql1 + ' and c.name = ? ';
            sql2 = sql2 + ' and c.name = ? ';
        }
        if(req.query.company.indexOf('选择') < 0) {
            params1.push(req.query.company);
            params2.push(req.query.company);
            sql1 = sql1 + ' and d.name = ? ';
            sql2 = sql2 + ' and d.name = ? ';
        }
        var lastSql = sql.enquiry.findRecordNormalCount1 + sql1 + ' union ' + sql2 + sql.enquiry.findRecordNormalCount2;
        var pageSize = util.pageSize();
        var params = params1.concat(params2);
        mysqlPool.getConnection(function (err, connection) {
            if (err) {
                res.json(util.toJson(code.DATABASE_CONNECTION_ERROR,'数据库连接错误'));
                return;
            }
            connection.query(lastSql, params, function (err, result) {
                if (err === null && result && result.length > 0){
                    var page = 0;
                    if (result.count % pageSize === 0) {
                        page = parseInt(result[0].count) / pageSize;
                    } else {
                        page = Math.floor(parseInt(result[0].count) / pageSize) + 1;
                    }
                    res.json(util.toJson(code.OPERATE_SUCCESS,'查询数目成功', {count:page}));
                } else {
                    res.json(util.toJson(1000 ,'查询数目失败'));
                }
                connection.release();
            })
        })
    },
    getDepartment:function (req, res) {
        if (util.isParameterEmpty(req.query.user_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req,'GET')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.getConnection(function (err, connection) {
            if (err) {
                res.json(util.toJson(code.DATABASE_CONNECTION_ERROR,'数据库连接错误'));
                return;
            }
            connection.query(sql.enquiry.findDepartment, [], function (err, result) {
                if (err === null && result && result.length > 0){
                    res.json(util.toJson(code.OPERATE_SUCCESS,'获取部门成功',result));
                } else {
                    res.json(util.toJson(1000 ,'获取部门失败'));
                }
                connection.release();
            })
        })
    },
    getCompany:function (req, res) {
        if (util.isParameterEmpty(req.query.user_id)){
            res.json(util.toJson(code.PARAMETER_IS_NULL, '参数不能为空'));
            return;
        }
        if (!util.isValidSession(req,'GET')) {
            res.json(util.toJson(code.SESSION_VALID, 'session失效，请重新登录'));
            return;
        }
        mysqlPool.getConnection(function (err, connection) {
            if (err) {
                res.json(util.toJson(code.DATABASE_CONNECTION_ERROR,'数据库连接错误'));
                return;
            }
            connection.query(sql.enquiry.findCompany, [], function (err, result) {
                if (err === null && result && result.length > 0){
                    res.json(util.toJson(code.OPERATE_SUCCESS,'获取供应商成功',result));
                } else {
                    res.json(util.toJson(1000 ,'获取供应商失败'));
                }
                connection.release();
            })
        })
    }
};
